﻿using System;
using GeoAPI.Geometries;

namespace NetTopologySuite.Algorithm
{
	[Obsolete("In some cases this algorithm makes a poor choice of endpoint. Replaced by a better heuristic in RobustLineIntersector")]
	public class CentralEndpointIntersector
	{
		public static Coordinate GetIntersection(Coordinate p00, Coordinate p01, Coordinate p10, Coordinate p11)
		{
			return new CentralEndpointIntersector(p00, p01, p10, p11).Intersection;
		}

		public CentralEndpointIntersector(Coordinate p00, Coordinate p01, Coordinate p10, Coordinate p11)
		{
			this._pts = new Coordinate[]
			{
				p00,
				p01,
				p10,
				p11
			};
			this.Compute();
		}

		private void OldCompute()
		{
			Coordinate p = CentralEndpointIntersector.Average(this._pts);
			this.Intersection = new Coordinate(CentralEndpointIntersector.FindNearestPoint(p, this._pts));
		}

		public Coordinate Intersection { get; private set; }

		private static Coordinate Average(Coordinate[] pts)
		{
			Coordinate coordinate = new Coordinate();
			int num = pts.Length;
			for (int i = 0; i < pts.Length; i++)
			{
				coordinate.X += pts[i].X;
				coordinate.Y += pts[i].Y;
			}
			if (num > 0)
			{
				coordinate.X /= (double)num;
				coordinate.Y /= (double)num;
			}
			return coordinate;
		}

		private static Coordinate FindNearestPoint(Coordinate p, Coordinate[] pts)
		{
			double num = double.MaxValue;
			Coordinate result = null;
			for (int i = 0; i < pts.Length; i++)
			{
				double num2 = p.Distance(pts[i]);
				if (i == 0 || num2 < num)
				{
					num = num2;
					result = pts[i];
				}
			}
			return result;
		}

		private void Compute()
		{
			this.TryDist(this._pts[0], this._pts[2], this._pts[3]);
			this.TryDist(this._pts[1], this._pts[2], this._pts[3]);
			this.TryDist(this._pts[2], this._pts[0], this._pts[1]);
			this.TryDist(this._pts[3], this._pts[0], this._pts[1]);
		}

		private void TryDist(Coordinate p, Coordinate p0, Coordinate p1)
		{
			double num = CGAlgorithms.DistancePointLine(p, p0, p1);
			if (num < this._minDist)
			{
				this._minDist = num;
				this.Intersection = p;
			}
		}

		private readonly Coordinate[] _pts;

		private double _minDist = double.MaxValue;
	}
}
